package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService executorService= Executors.newFixedThreadPool(10);

    @Override
    public Result queryShopById(Long id) {
        //互斥锁解决缓存击穿
        Shop shop = queryWithMutex(id);
//        //逻辑过期解决缓存击穿
//        Shop shop = queryWithLogicalExpire(id);
        if(shop==null){
            return Result.fail("商铺不存在");
        }
        return Result.ok(shop);
    }

    private Shop queryWithMutex(Long id){
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if(StrUtil.isNotBlank(json)){
            Shop shop = JSONUtil.toBean(json, Shop.class);
            return shop;
        }
        //如果是空值返回null，减少数据库的压力
        if("".equals(json)){
            return null;
        }
        //互斥锁解决缓存击穿
        boolean isLock = tryLock(LOCK_SHOP_KEY + id);
        Shop shop = null;
        try {
            if (!isLock) {
                Thread.sleep(50);
                queryWithMutex(id);
            }
            String json2 = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
            if(StrUtil.isNotBlank(json2)){
                shop = JSONUtil.toBean(json2, Shop.class);
                return shop;
            }
            shop = getById(id);
            if(shop==null){
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unLock(LOCK_SHOP_KEY + id);
        }
        return shop;
    }

    //逻辑过期解决缓存击穿，只处理热点key，不处理普通key
    private Shop queryWithLogicalExpire(Long id){
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if(StrUtil.isBlank(json)){
            return null;
        }
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject jsonObject= (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(jsonObject, Shop.class);
        if(LocalDateTime.now().isBefore(redisData.getExpireTime())){
            return shop;
        }
        boolean lock = tryLock(LOCK_SHOP_KEY + id);
        if(lock){
            //开启线程重建缓存
            executorService.submit(()->{
                try {
                    Shop shop1 = getById(id);
                    RedisData redisData1=new RedisData();
                    redisData1.setExpireTime(LocalDateTime.now().plusSeconds(20L));
                    redisData1.setData(shop1);
                    stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData1));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(LOCK_SHOP_KEY + id);
                }
            });

        }
        return shop;
    }

    private boolean tryLock(String key){
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10L, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if(id==null){
            return Result.fail("店铺id不存在");
        }
        //更新数据库
        updateById(shop);
        //删缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }
}
